package com.xlserver.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xlserver.dao.ConsultationMapper;
import com.xlserver.dao.CounselorMapper;
import com.xlserver.dao.UserMapper;
import com.xlserver.domain.Consultation;
import com.xlserver.domain.Counselor;
import com.xlserver.domain.User;
import com.xlserver.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket/{cid}")
@RestController
public class WebSocketController {
    private static Session session;

    /**
     * 连接集合
     */
    private static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    private static MessageService messageService;
    private static ConsultationMapper consultationMapper;
    private static UserMapper userMapper;
    private static CounselorMapper counselorMapper;
    @Autowired
    public void setChatService(MessageService messageService,
                               ConsultationMapper consultationMapper,
                               UserMapper userMapper,
                               CounselorMapper counselorMapper) {
        WebSocketController.messageService = messageService;
        WebSocketController.consultationMapper = consultationMapper;
        WebSocketController.userMapper = userMapper;
        WebSocketController.counselorMapper = counselorMapper;
    }
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,
                       @PathParam("cid") String cid) {
        int counselorId = Integer.parseInt(cid);
        //添加到集合中
        sessionMap.put(cid, session);
        //获取日志信息
        new Thread(() -> {
            while (sessionMap.get(cid) != null) {
                JSONArray queue = waitQueue(counselorId);
                System.out.println("等待队列"+queue);
                send(session, queue.toJSONString());
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public JSONArray waitQueue(int cid){
        JSONArray res = new JSONArray();
        consultationMapper.selectList(new QueryWrapper<Consultation>()
                .eq("cid",cid)).forEach(consultation -> {
                    if (consultation.getBeginTime().equals(consultation.getEndTime())){
                        if (cid < 30000 && cid >= 20000){
                            JSONObject userInfo = new JSONObject();
                            User user = userMapper.selectById(consultation.getUid());
                            userInfo.put("avatar",user.getProfilePhoto());
                            userInfo.put("name",user.getUsername());
                            userInfo.put("id",user.getUserId());
                            res.add(userInfo);
                        }
                        else if (cid >= 30000){
                            JSONObject userInfo = new JSONObject();
                            Counselor user = counselorMapper.selectById(consultation.getUid());
                            userInfo.put("avatar",user.getProfilePhoto());
                            userInfo.put("name",user.getUsername());
                            userInfo.put("id",user.getCid());
                            res.add(userInfo);
                        }
                    }
        });
        return res;
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session,
                        @PathParam("cid") String cid) {
        //从集合中删除
        sessionMap.remove(cid);
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {

    }

    /**
     * 封装一个send方法，发送消息到前端
     */
    private void send(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

